package 回溯;

import java.util.*;

public class LeetCode47_全排列 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if(len == 0) {
            return res;
        }
        Stack<Integer> path = new Stack<>();
        boolean[] used = new boolean[len];
        dfs(nums, len, 0, path, used, res);
        return res;
    }

    private void dfs(int[] nums, int len, int depth, Stack<Integer> path, boolean[] used, List<List<Integer>> res) {

        if(depth == len) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if(used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) {
                // 已经选过了，不需要再操作
                continue;
            }
            path.push(nums[i]);
            used[i] = true;
            dfs(nums, len, depth+1, path, used, res);
            path.pop();
            used[i] = false;
        }
    }
}
